#include <stdio.h>
#include <string.h>

// 函数声明
int asc2hex(unsigned char bKey, unsigned char *bNew);
int str2hex(unsigned char *lpRead, unsigned char *lpWrite, int dwCount);

int main()
{
    // 测试字符串
    unsigned char input[] = "0000007a30333033";
    // 输出缓冲区
    unsigned char output[100] = {0};
    // 输入字符串长度
    int length = strlen((char *)input);

    // 调用 str2hex 函数
    int result = str2hex(input, output, length);

    if (result == 0)
    {
        printf("转换成功！\n");
        printf("输入字符串: %s\n", input);
        printf("输出十六进制数据: ");
        for (int i = 0; i < length / 2; i++)
        {
            printf("%02X ", output[i]);
        }
        printf("\n");
    }
    else
    {
        printf("转换失败！\n");
    }

    return 0;
}

// 函数定义
int asc2hex(unsigned char bKey, unsigned char *bNew)
{
    if ((bKey >= '0') && (bKey <= '9'))
    {
        *bNew = bKey - '0';
    }
    else if ((bKey >= 'A') && (bKey <= 'F'))
    {
        *bNew = bKey - 'A' + 10;
    }
    else if ((bKey >= 'a') && (bKey <= 'f'))
    {
        *bNew = bKey - 'a' + 10;
    }
    else
    {
        return -1;
    }
    return 0;
}

int str2hex(unsigned char *lpRead, unsigned char *lpWrite, int dwCount)
{
    unsigned char bNew;

    while (dwCount--)
    {
        if (asc2hex(*lpRead++, &bNew) == -1)
            return -1;

        *lpWrite = *lpWrite << 4 | bNew;

        if (!(dwCount & 0x01))
            ++lpWrite;
    }
    return 0;
}